package org.korosoft.rusalad.syncnrun.tools;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.AbstractQueuedSynchronizer;

/**
 * An analogue to {@link java.util.concurrent.CountDownLatch} class with countUp functionality.
 * await() unblocks either immediately (if current counter is 0) or when counters becomes equal to zero.
 *
 * @author Dmitry Korotkov
 * @since 1.0
 */
public class CountUpAndDownLatch {

    private static class Sync extends AbstractQueuedSynchronizer {
        private Sync(int count) {
            setState(count);
        }

        @Override
        protected int tryAcquireShared(int arg) {
            return getState() == 0 ? 1 : -1;
        }

        private int getCount() {
            return getState();
        }

        @Override
        protected boolean tryReleaseShared(int arg) {
            for (; ; ) {
                int c = getState();
                if (c == 0)
                    return false;
                int nextc = c - 1;
                if (compareAndSetState(c, nextc))
                    return nextc == 0;
            }
        }

        private void countUp() {
            for (; ; ) {
                final int c = getState();
                final int nextc = c + 1;
                if (compareAndSetState(c, nextc)) {
                    return;
                }
            }
        }
    }

    private final Sync sync;

    public CountUpAndDownLatch() {
        sync = new Sync(0);
    }

    public CountUpAndDownLatch(int initialCount) {
        sync = new Sync(initialCount);
    }

    public void await() throws InterruptedException {
        sync.acquireSharedInterruptibly(1);
    }

    public boolean await(long timeout, TimeUnit unit)
            throws InterruptedException {
        return sync.tryAcquireSharedNanos(1, unit.toNanos(timeout));
    }

    public void countDown() {
        sync.releaseShared(1);
    }

    public void countUp() {
        sync.countUp();
    }

    public long getCount() {
        return sync.getCount();
    }

    public String toString() {
        return super.toString() + "[Count = " + sync.getCount() + "]";
    }
}
